<template>
  <div>
    <div class="title">
      <h2>论坛</h2>
    </div>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="auto"
      class="demo-ruleForm login"
    >
      <el-form-item label="用户名" prop="user">
        <el-input v-model.number="ruleForm.user"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item class="btn" label-width="auto">
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="footer">
      <p class="noUser">
        没有账号？去
        <router-link to="/home/register">注册</router-link>
      </p>
      <router-link to="/home/forget">忘记密码</router-link>
    </div>
  </div>
</template>

<script>
import { toLogin } from "../api/luntan-api";
export default {
  data() {
    var checkUser = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("用户名不能为空"));
      }
      setTimeout(() => {
        callback();
      }, 1000);
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      }
      setTimeout(() => {
        callback();
      }, 1000);
    };
    return {
      ruleForm: {
        user: "",
        pass: ""
      },
      rules: {
        user: [{ validator: checkUser, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          toLogin(this.ruleForm.user, this.ruleForm.pass).then(res => {
            if (res.code == 0) {
              this.$store.commit({
                type: "loginsucess",
                user: res.data
              });
              localStorage.setItem("myToTag", "1");
              this.$router.push({ path: "/home/me" });
            } else {
              this.$notify.error({
                message: res.msg,
                duration: 2000
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style lang="less" scoped>
.title {
  width: 100%;
  height: 120px;
  margin-top: 50px;
}
.login {
  width: 90%;
  margin-left: 20px;
}
.noUser {
  margin-top: 50px;
}
</style>